package cn.edu.zjgsu.ito.controller;

import cn.edu.zjgsu.ito.interceptor.AdminControllerInterceptor;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;














import cn.edu.zjgsu.ito.model.Major;
import cn.edu.zjgsu.ito.model.StudentInfo;
import cn.edu.zjgsu.ito.service.AdminExportStuService;
import cn.edu.zjgsu.ito.service.AdminStuManageService;
import cn.edu.zjgsu.ito.service.ServiceFactory;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.core.JFinal;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.PathKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;


@Before(AdminControllerInterceptor.class)
public class AdminStuManageController extends Controller {

	AdminStuManageService adminStuManageService=ServiceFactory.createAdminStuManageService();
	public static final DateFormat formatter=new SimpleDateFormat("yyyyMMddHHmmss");

	/**
	 * 更新护照号
	 * 刘阳
	 */
	public void updatenewpassportNo(){
		String passportNo = getPara("passportNo");
		String newpassportNo = getPara("newpassportNo");
		String time = getPara("time");
		Record newpassportno = new Record();
		newpassportno.set("passportNo", passportNo);
		newpassportno.set("newpassportNo", newpassportNo);
		newpassportno.set("time", time);
		String error = adminStuManageService.addnewpassportNo(newpassportno);
		List<Record> information = adminStuManageService.looks(newpassportno);
		setAttr("error",error);
		renderJson(information);
	}
	/**
	 * 删除加错的护照号
	 * 刘阳
	 */
	public void ajaxdeletenewpassportNo(){
		System.out.println("weege");
		String newpassportNo = getPara("newpassportNo");
		String error = adminStuManageService.deletenewpassport(newpassportNo);
		setAttr("error",error);
		renderJson();
	}
	/**
	 * 查看以往护照号
	 * 刘阳
	 */
	public void ajaxlook(){
		String passportNo = getPara("passportNo");
		List<Record> newpassportno = Db.find("select * from newpassportno where passportNo=?",passportNo);
		renderJson(newpassportno);
	}
	/**
	 * 查看以往转专业信息
	 * 刘阳
	 */
	public void ajaxlookmajor(){
		String sNo = getPara("sNo");
		System.out.println(sNo);
		List<Record> majorhistory = Db.find("select * from transfermajor where sNo=?",sNo);
		System.out.println("rrrrrrrrrr");
		System.out.println(majorhistory);
		renderJson(majorhistory);
		System.out.println("qqqqqqqqqqqqq");
	}
	/**
	 * 点击护照号显示学生信息
	 * 刘阳
	 * @throws ParseException 
	 */
	public void lookup() throws ParseException{
		String passportNo = getPara("passportNo");
		System.out.println(passportNo);
		System.out.println("----------------------------------??????????????????");
		StudentInfo studentInfo = getModel(StudentInfo.class);
		studentInfo.set("passportNo",passportNo);
		System.out.println("<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>");		
		Record error=adminStuManageService.look(studentInfo);
		System.out.println("\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\");
		System.out.println(error.getStr("passportNo"));
		System.out.println("=======");
		System.out.println(error.getStr("newpassportNo"));
		String temp = null;
		temp = JsonKit.toJson(error);		
		renderJson(temp);

	}
	/**
	 * 学生管理初始化
	 * 黄凯航
	 * @throws ParseException 
	 */
	public void index() throws ParseException
	{
		//		List<Record> studentInfos=Db.find("select * from student_info");
		List<Record> studentInfos = adminStuManageService.studentManage();
		setAttr("studentInfo",studentInfos);
		List<Record> term = Db.find("select * from term");
		setAttr("term",term);
		System.out.println("aaa");
		System.out.println(studentInfos);
		render("studentmanage.html");
	}
	/**
	 * 添加学院页面跳转
	 * 黄凯航
	 */
	public void add()
	{
		setAttr("majorName",Db.find("select majorName from major"));
		render("addstudent.html");
	}
	/**
	 * 添加学生
	 * 黄凯航
	 * @throws ParseException 
	 */
	public void submit() throws ParseException
	{
		StudentInfo studentInfo=getModel(StudentInfo.class,"studentInfo");
		String error=adminStuManageService.addSingleStudent(studentInfo);	
		setAttr("error",error);
		renderJson();
		index();

	}
	/**
	 * 编辑学生页面跳转
	 * 黄凯航
	 * @throws ParseException 
	 */
	public void edit() throws ParseException
	{
		java.text.SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		Integer id=getParaToInt(0);
		if(id!=null&&id>0)
		{
			//			StudentInfo studentInfo = StudentInfo.dao.findById(id);
			Record studentInfo = Db.findFirst("select * from student_info where id=?",id);
			String passportNo = studentInfo.getStr("passportNo");
			System.out.println(passportNo);
			String []b= new String[100];
			Date []date=new Date[100];
			Date dates=new Date();
			String Dates="";
			List<Record> studentInfos = Db.find("select * from newpassportno where passportNo=?",passportNo);
			if(studentInfos.size()>1){
				for(int j=0;j<studentInfos.size();j++){
					b[j] = studentInfos.get(j).getStr("time");
					date[j] = formatter.parse(b[j]);
				}
				System.out.println(studentInfos.size());
				for(int a=0;a<studentInfos.size()-1;a++){
					dates = date[a];
					int c = (date[a+1]).compareTo(dates);

					if(c>0){
						dates = date[a+1];
					}

				}

				Dates = formatter.format(dates);

				Record newpassportNo = Db.findFirst("select * from newpassportno where time=?",Dates);

				studentInfo.set("newpassportNo",newpassportNo.getStr("newpassportNo"));
			}
			else{

				Record newpassportNo = Db.findFirst("select * from newpassportno where passportNo=?",passportNo);

				studentInfo.set("newpassportNo",newpassportNo.getStr("newpassportNo"));
			}	
			System.out.println(studentInfo);
			
			String stuClass = studentInfo.getStr("class");
			System.out.println("学生班级:"+studentInfo.getStr("class"));
			studentInfo.set("stuClass",stuClass);
			
//			List<Record> studentInfoes = new ArrayList<Record>();
//			for(Record e : Db.find("select class from student_info group by class")){
//				Record r = new Record();
//				r.set("clazz", e.get("class"));
//				if("".equals(r.get("class")))
//					r.set("clazz", null);
//				if(!studentInfoes.contains(r)){
//					studentInfoes.add(r);
//				}
//			}

			setAttr("studentInfo",studentInfo);
			System.out.println("wwwww");
			System.out.println(studentInfo);
			setAttr("allclass",Db.find("select class from student_info group by class"));

			
			setAttr("majorName",Db.find("select majorName from major"));
		}
		render("correctstudent.html");
	}

	/**
	 * 更新学生
	 * 黄凯航
	 * @throws ParseException 
	 */
	public void update() throws ParseException
	{	
		StudentInfo studentInfo=getModel(StudentInfo.class,"studentInfo");	
		String error=adminStuManageService.updateSingleStudent(studentInfo);
		setAttr("error",error);
		index();

	}
	/**
	 * 学生搜索
	 * 黄凯航
	 */
	public void search()
	{
		String keyword=getPara("keyword").trim();

		List<Record> studentInfos=Db.find("select * from student_info where passportNo like ?","%"+keyword+"%");
		studentInfos.addAll(Db.find("select * from student_info where lastName like ?","%"+keyword+"%"));
		studentInfos.addAll(Db.find("select * from student_info where firstName like ?","%"+keyword+"%"));

		HashSet<Record> c=new HashSet<Record>(studentInfos);
		studentInfos.clear();
		studentInfos.addAll(c);

		setAttr("studentInfo",studentInfos);
		render("studentmanage.html");
	}
	/**
	 * 异步学生搜索
	 * 黄凯航
	 */
	public void ajaxsearch()
	{
		String keyword=getPara("keyword");

		List<StudentInfo> studentInfo=StudentInfo.dao.find("select * from student_info where passportNo like ?","%"+keyword+"%");
		studentInfo.addAll(StudentInfo.dao.find("select * from student_info where lastName like ?","%"+keyword+"%"));
		studentInfo.addAll(StudentInfo.dao.find("select * from student_info where firstName like ?","%"+keyword+"%"));

		HashSet<StudentInfo> c=new HashSet<StudentInfo>(studentInfo);
		studentInfo.clear();
		studentInfo.addAll(c);
		renderJson(studentInfo);	    

	}
	/**
	 * 异步学生隐藏
	 * 黄凯航
	 */
	public void ajaxnone()
	{
		String keyword=getPara("none");
		List<StudentInfo> studentInfo = null;
		if(keyword.equals("0"))
			studentInfo=StudentInfo.dao.find("select * from student_info ");
		if(keyword.equals("1"))	
			studentInfo=StudentInfo.dao.find("select * from student_info where studentStatus=?",1);
		renderJson(studentInfo);	    
	}
	/**
	 * 学生批量处理方法
	 * 黄凯航
	 */
	public void batch()
	{
		try{
			String action=getPara("action");
			int id=0;
			String passportNo="";
			Record studentPassportNo=new Record();
			//String[] stuCheckboxs=getParaValues("stuCheckbox");
			String checkboxValue=getPara("checkboxValue");
			String[] stuCheckboxs= checkboxValue.split(",");
			for(int i=0;i<stuCheckboxs.length;i++)
				System.out.print(i+"="+stuCheckboxs[i]+"  ");
			//失效操作
			if(action.equals("invalid"))
			{
				for(int i=0;i<stuCheckboxs.length;i++)
				{
					id=Integer.parseInt(stuCheckboxs[i]);
					adminStuManageService.changeStatus(id);
				}
			}
			//删除操作
			if(action.equals("delete"))
			{
				for(int i=0;i<stuCheckboxs.length;i++)
				{
					id=Integer.parseInt(stuCheckboxs[i]);
					studentPassportNo=Db.findById("student_info", id);
					passportNo = studentPassportNo.get("passportNo");
					adminStuManageService.deleteOrNot(passportNo);
					studentPassportNo=new Record();
				}
			}
			//密码重置
			if(action.equals("re"))
			{
				for(int i=0;i<stuCheckboxs.length;i++)
				{
					id=Integer.parseInt(stuCheckboxs[i]);
					studentPassportNo=Db.findById("student_info", id);
					passportNo = studentPassportNo.get("passportNo");
					adminStuManageService.rePassword(passportNo);
					studentPassportNo=new Record();
				}
			}
			redirect("/adminstumanage");
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			redirect("/adminstumanage");
		}

	}
	/**
	 * 学生模板下载方法
	 * 黄凯航
	 */
	public void fileDownload()
	{
		String fileName="学生模板.xls";
		String path=JFinal.me().getConstants().getFileRenderPath();
		path=path+"/"+fileName;
		renderFile(new File(path));
	}
	/**
	 * 学生模板上传方法
	 * 黄凯航
	 */
	public void fileUpload()
	{
		String filedir=PathKit.getWebRootPath();
		filedir=filedir+"\\WEB-INF\\upload";
		try
		{
			UploadFile file=getFile("uploadFile");
			String fileName=file.getFileName();
			String extension=fileName.substring(fileName.lastIndexOf("."));
			if(extension.equals(".xls")||extension.equals(".XLS"))
			{
				File source=file.getFile();
				String newFileName=System.currentTimeMillis()+extension;
				FileInputStream fis=new FileInputStream(source);
				File targetDir=new File(filedir);
				File target=new File(targetDir,newFileName);
				FileOutputStream fos=new FileOutputStream(target);
				byte[] bts=new byte[300];
				while (fis.read(bts,0,300)!=-1){
					fos.write(bts,0,300);
				}
				fos.close();
				fis.close();
				source.delete();
				String error=adminStuManageService.readStudentTemplate(fileName, newFileName, filedir);
				setAttr("error",error);
				index();
			}
			else
			{
				setAttr("error","文件类型错误");
				index();
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}

	/**
	 *导出学生课表
	 *autor 杨昆鹏 
	 * */
	public void exportTimetable(){
		System.out.println("导出课表！！！");
		String temp = getPara("passportNo");
		String term = getPara("team");
		System.out.println("查询学期:"+term);
		String[] passportNoes = temp.split(",");
		for(int i = 0;i < passportNoes.length;i++){
			System.out.println("拿到的护照号是：" + passportNoes[i]);
		}
		//		护照号，输出流
		String stuName = "";
		OutputStream out = null;

		Date date = new Date();
		String time=formatter.format(date);

		System.out.println(time);

		String filedir=PathKit.getWebRootPath();
		filedir=filedir+"\\WEB-INF\\download\\";
		deleteFile(new File(filedir));//清空缓存区

		String[] paths = new String[passportNoes.length];
		String[] stuNames = new String[passportNoes.length];
		try {
			for(int i = 0;i < passportNoes.length;i++){
				stuName = "";
				time=formatter.format(date);
				Record port = Db.findFirst("select newpassportNo from newpassportno where passportNo=?",passportNoes[i]);
				String newpassportNo = port.getStr("newpassportNo");
				stuName= newpassportNo + stuName + time + ".xls";
				String outpath = filedir+stuName;
				out = new FileOutputStream(outpath);
				System.out.println(filedir+stuName);
				adminStuManageService.timetable(passportNoes[i], out,term);
				paths[i] = outpath;
				stuNames[i] = stuName;
			}
			String path = filedir + "/" + "学生课表" +".zip";
			adminStuManageService.zipModel(paths,stuNames,filedir);
			renderFile(new File(path));
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
//		finally{
//			try {
//				out.close();
//			} catch (IOException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//		}	 		

	}

	public void deleteFile(File oldPath) {
		if (oldPath.isDirectory()) {
			File[] files = oldPath.listFiles();
			for (File file : files) {
				deleteFile(file);
			}
		}else{
			oldPath.delete();
		}
	}

}
